package com.mdsi;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import java.io.InputStream;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet Filter implementation class StaticFilter
 */
@WebFilter("/Static/*")
public class StaticFilter implements Filter {

    /**
     * Default constructor. 
     */
    public StaticFilter() {
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest)request ;
		HttpServletResponse httpResponse = (HttpServletResponse)response ;
		File file = new File(httpRequest.getServletContext().getRealPath(httpRequest.getRequestURI().substring(httpRequest.getRequestURI().indexOf('/', 1)))) ;
	    byte buffer[] = new byte[8192];
	    int bytesRead;
	    InputStream is = new FileInputStream(file) ;
	    OutputStream os = httpResponse.getOutputStream() ;
	    BufferedInputStream bis = new BufferedInputStream(is);
	    while ((bytesRead = bis.read(buffer)) != -1) {
	        os.write(buffer, 0, bytesRead);
	    }
	    is.close();
	    os.flush();
	    os.close();
	    httpResponse.setHeader("Content-Type", "text/css") ;
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
	}

}
